package com.gzz.core.util;

import javax.xml.bind.DatatypeConverter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * ObjectUtil.java,用于对象的序列化
 *
 */
public class ObjectUtil {
    /**
     * 把对象转成字符串
     */
    public static String objectToString(Object obj) {
        // 对象转字节数组
        AtomicReference<String> str = new AtomicReference<>();
        Optional.ofNullable(obj).ifPresent(o -> {
            try {
                byte[] bytes = writeObj(o);
                str.set(DatatypeConverter.printBase64Binary(bytes));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return str.get();
    }

    /**
     * 解析字符串为对象
     */
    public static Object stringToObject(String str) {
        AtomicReference<Object> obj = new AtomicReference<>();
        Optional.ofNullable(str).ifPresent(s -> {
            try {
                byte[] bytes = DatatypeConverter.parseBase64Binary(str);
                obj.set(readObj(bytes));
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        return obj.get();
    }

    /**
     把对象转为字节数组
     */
    public static byte[] writeObj(Object obj) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream);
        outputStream.writeObject(obj);
        outputStream.close();
        return byteArrayOutputStream.toByteArray();
    }
    /**
     把字节数组转为对象
     */
    public static Object readObj(byte[] bytes) throws Exception {
        ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
            return inputStream.readObject();
        } finally {
            inputStream.close();
        }
    }
}
